package com.ssm.server.sys;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssm.server.common.JsonData;
import com.ssm.server.consts.CodeEnum;
import com.ssm.server.consts.EncodeConstant;
import com.ssm.server.util.ParserParamUtil;
import com.ssm.server.util.TokenUse;


/**
 * 做用户token认证处理
 * @author lidongdong
 * 2017年12月15日 上午11:13:09
 */
public class ValidateInterCeptor implements HandlerInterceptor {
	
	private static final Logger LOGGER = Logger.getLogger(ValidateInterCeptor.class);
	private List<String> extendUrl = null;
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView)
			throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		JsonData json = new JsonData();
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding(EncodeConstant.UTF8);
		try {
			String interfaceName = request.getServletPath();
			//不进行拦截处理的链接
			if (extendUrl.contains(interfaceName)) {
				return true;
			}
			
			//接口合法性验证
			Map<String, String> param = new HashMap<>();
//			if(token==null){
//				
//				StringBuilder sb = new StringBuilder();
//		        try {
//		        BufferedReader reader = request.getReader();
//	
//				char[]buff = new char[1024];
//			
//				int len;
//			
//				while((len = reader.read(buff)) != -1) {
//				        sb.append(buff,0, len);
//				}
//				        } catch (IOException e) {
//				        e.printStackTrace();
//				        }
//		        String stringBuf = sb.toString();
//	        	String substring = stringBuf.substring(0,stringBuf.length());//截取最后一个
//				LOGGER.error("截取订单id符串后"+substring);
//				String[] split = substring.split("&");//以逗号分割
//				int mapLength = split.length;
//				//判断hashMap的长度是否是2的幂。
//				if((split.length % 2) != 0){
//					mapLength = mapLength+1;
//				}
//
//				Map<String,String> map = new HashMap<>(mapLength);
//				//循环加入map集合
//				for (int i = 0; i < split.length; i++) {
//					//截取一组字符串
//					String[] strArray = split[i].split("=");
//					//strArray[0]为KEY  strArray[1]为值]
//					if(strArray.length==2){
//						map.put(strArray[0],strArray[1]);
//					}
//				}
//				token=map.get("token");
//			}
			String[] path=interfaceName.split("/");
			if (!path[1].equals("security")) {
				String token = request.getParameter("token");
				if (StringUtils.isEmpty(token)) {
					json.setCodeEnum(CodeEnum.ERROR_TOKEN);
					response.getWriter().print(JSON.toJSONString(json));
					return false;
				}
				boolean bo = TokenUse.tokenVerify(token);
				if (bo == false) {
					LOGGER.info("登录失效:" + token);
	            	json.setCodeEnum(CodeEnum.USER_PUSH_OUT_CHAOSHI);
					response.getWriter().println(JSON.toJSONString(json));
					return false;
				}
			}
				Map<String, String[]> map = request.getParameterMap();
				 for(Entry<String, String[]> entry : map.entrySet()){
				 param.put(entry.getKey(), entry.getValue()[0] == null ? null :
				 URLDecoder.decode(entry.getValue()[0],
				 StandardCharsets.UTF_8.toString()));
				 }
				 LOGGER.info("-------------" + interfaceName +
				 "的请求参数为-------------" + param);
				 interfaceName =
				 interfaceName.substring(interfaceName.lastIndexOf("/") + 1,
				 interfaceName.length());
				
//				 if (!ParserParamUtil.authRequest(interfaceName, param)) {
//				 LOGGER.info("-------------接口参数验证失败-------------");
//			     json.setCodeEnum(CodeEnum.BAD_PARAMETER);
//				 response.getWriter().print(JSON.toJSONString(json));
//				 return false;
//			 }
		} catch (Exception e) {
			LOGGER.error("处理请求出错",e);
			json.setCodeEnum(CodeEnum.ERROR);
			response.getWriter().print(JSON.toJSONString(json));
			return false;
		}
		return true;
	}

	public List<String> getExtendUrl() {
		return extendUrl;
	}

	public void setExtendUrl(List<String> extendUrl) {
		this.extendUrl = extendUrl;
	}
}
